# @FileName  : main.py
# @Time      : 2023/11/20 9:15
# @Author    : LuZhaoHui
# @Software  : data-ocr

# 档案数据：修改初始文件名，分析ocr数据，根据凭证修改文件名称

# from PyQt5.QtWidgets import *
# from PyQt5.QtCore import *
# from PyQt5.QtGui import *
import json
import os.path
import re

from tool import *

IMAGE_PATH = 'f:/image/haidian'
RESULT_PATH = 'f:/image/haidian-result'

imageLogFile = ''
imageSrcDir = ''
imageDirList = []
imageFileDict = {}
resultSrcDir = ''


# 扫描文件目录
# def getImageFiles(dir, imgList=[]):
#     for root, ds, fs in temp:
#         if root == dir and len(fs) == 0:
#             continue
#         if len(ds) == 0:
#             fs = sorted(fs)
#             for f in fs:
#                 name = os.path.join(root, f)
#                 sname = os.path.basename(name)
#                 snums = sname.split('_')
#                 # 是否凭证
#                 if len(snums) < 3:
#                     continue
#                 if (os.path.splitext(name.lower())[1] in type):
#                     files.append(name)
#     return files

def getOcrResult(data):
    text = ''
    if len(data) > 0:
        if 'lines' in data[0].keys():
            lines = data[0]['lines']
            for value in lines:
                if 'text' not in value.keys():
                    continue
                text += value['text'].replace('\'', '').replace('\"', '')
    return text


def getOcrText(name):
    # files = []
    dict = {}
    datas = []
    with open(name, 'r', encoding='utf-8') as f:
        try:
            data = f.read()
            dict = ast.literal_eval(data)
            # files = list(dict.keys())
            datas = list(dict.values())
        except Exception as e:
            print(e)
    return getOcrResult(datas)


def getTextVouch(text):
    isVouch = False
    vouchNo = ''
    vouchPos = ''
    vouchDate = ''
    while True:
        pos = text.find('记账凭证')
        if pos < 0:
            break
        nextText = text[pos + 4:]
        pos = nextText.find('第')
        if pos < 0:
            break
        nextText = nextText[pos + 1:]
        if nextText[4] != '号':
            break
        if not nextText[:4].isdigit():
            break
        # 凭证号
        vouchNo = nextText[:4]
        vouchPos = '0001'
        isVouch = True
        if nextText[5] == '-':
            nextText = nextText[6:]
            if nextText[4] == '/' and nextText[:4].isdigit():
                vouchPos = nextText[:4]
        # 日期
        pos = text.find('日期')
        if pos > 0:
            # xxxx-xx-xx
            nextText = text[pos + 2:]
            for ch in nextText:
                if ch == ':':
                    continue
                if ch != '-' and not ch.isdigit():
                    break
                vouchDate += ch
            break
        # xxxx年xx月xx日
        regex = r"\d{4}年\d{1,2}月\d{1,2}日"
        ymd = re.findall(regex, text)
        if len(ymd) > 0:
            vouchDate = ymd[0].replace('年', '-').replace('月', '-').replace('日', '')
        break
    return isVouch, vouchNo, vouchPos, vouchDate


def procImageFile(name):
    imageDirList.clear()
    imageFileDict.clear()
    imageLogFile = pathJoin(IMAGE_PATH, name + '.lst')
    writeLog('', imageLogFile)
    imageSrcDir = pathJoin(IMAGE_PATH, name)
    resultSrcDir = pathJoin(RESULT_PATH, name)
    temp = sorted(os.walk(imageSrcDir))
    for root, ds, fs in temp:
        if root == imageSrcDir and len(fs) == 0:
            # 目录->目录
            for d in ds:
                imageDirList.append(d)
                imageFileDict[pathJoin(imageSrcDir, d)] = []
            continue
        if len(ds) == 0:
            # 目录->文件
            d = root.replace('\\', '/')
            if d in imageFileDict.keys():
                # 目录
                for f in fs:
                    # pos,src,ocr,text,isVouch,vouchNo,vouchPos,vouchDate
                    if os.path.splitext(f)[1] != '.jpg':
                        continue
                    info = {}
                    info['imageName'] = pathJoin(d, f)
                    print(info['imageName'])
                    rd = pathJoin(resultSrcDir, os.path.basename(d))
                    rf = os.path.splitext(f)[0]
                    rfList = rf.split('-')
                    if len(rfList) > 2:
                        del rfList[2:]
                    rf = ''
                    for r in rfList:
                        if rf != '':
                            rf += '-'
                        rf += r
                    rf = pathJoin(rd, rf + '.txt')
                    info['ocr'] = ''
                    info['text'] = ''
                    if os.path.isfile(rf):
                        info['ocr'] = rf
                        info['text'] = getOcrText(rf)
                    info['isVouch'], info['vouchNo'], info['vouchPos'], info['vouchDate'] = getTextVouch(info['text'])
                    imageFileDict[d].append(info)
                # 判断目录改名
                for i, dd in enumerate(imageFileDict[d]):
                    dname = os.path.dirname(dd['imageName'])
                    fname = os.path.basename(dd['imageName'])
                    isOcr = len(dd['ocr']) > 0
                    if isOcr:
                        rdname = os.path.dirname(dd['ocr'])
                        rfname = os.path.basename(dd['ocr'])
                    newName = '%s-%06d' % (os.path.basename(dname), i + 1)
                    if isOcr:
                        newRname = '%s-%06d%s' % (os.path.basename(rdname), i + 1, os.path.splitext(rfname)[1])
                    if dd['isVouch']:
                        # 凭证号
                        newName += '-%s-%s' % (dd['vouchNo'], dd['vouchPos'])
                    newName += os.path.splitext(fname)[1]
                    imageName = pathJoin(dname, newName)
                    if dd['imageName'] != imageName:
                        # 改名
                        os.rename(dd['imageName'], imageName)
                        dd['imageName'] = imageName
                    if isOcr:
                        ocrName = pathJoin(rdname, newRname)
                        if dd['ocr'] != ocrName:
                            # 改名
                            os.rename(dd['ocr'], ocrName)
                            dd['ocr'] = ocrName
                    writeLog(json.dumps(dd), imageLogFile)
            continue


if __name__ == '__main__':
    # 初始文件名
    procImageFile('2017')
    procImageFile('2022')
    # procImageFile('2018')
    # procImageFile('2020')

    # app = QApplication(sys.argv)
    #
    # main = bxgdataRun()
    # main.show()
    #
    # sys.exit(app.exec_())
